# -*- coding: utf-8 -*-
#!/usr/bin/env python
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import logging

from sms.TmpFetion import TmpFetion
from weather.model import *
from base import *
from util import *
import gmemsess
from weather.weather_collect import WeatherCollect

def makeWeather(city,date):
    query = WeatherStore.all().filter('date =',date).filter('city =',city.key())
    if query.count()>0:
        logging.info('*************find weather *************')
        return query[0]
    else:
        logging.info('*************not find weather*************')
        wc = WeatherCollect(city.url)
        msg = wc.get_weather()
        logging.info('*************weather message %s *************'%msg)
        if msg:
            wether = WeatherStore()
            wether.date = today_str()
            wether.city = city
            wether.message = msg
            wether.put()
            return wether
    return u'程序异常,稍后重发!'

class MainPage(BaseRequestHandler):
    def get(self):
        self.render('template/weather/index.html')

class Login(BaseRequestHandler):
    
    def post(self):
        msg = ''
        username = self.request.get('username')
        password = self.request.get('password')
        if username and password:
            query = User.all().filter('username =', username)
            if query.count()>0:
                query = query[0]
                if query.password != password:
                    msg = u'密码输入错误,请重试!'
                else:
                    query.last_ip = self.request.remote_addr
                    query.last_login = today()
                    query.put()
                    sess = gmemsess.Session(self)
                    sess['username'] = username
                    sess['user_key'] = query.key()
                    sess.save()
                    logging.info('%s Login success!'%username)
                    self.redirect('/admin')
            else:
                msg = u'您输入的用户名密码不正确!'
        else:
            msg = u'用户名或密码不能为空!'
        
        self.render('template/weather/index.html',{'msg':msg})

class AdminPage(BaseRequestHandler):
    
    @checkLogin
    def get(self):
        user = User.get(getUserKey(self))
        self.render('template/weather/user.html',{'user':user})

class Registe(BaseRequestHandler):
    def post(self):
        msg = ''
        username = self.request.get('username')
        password = self.request.get('password')
        repassword = self.request.get('repassword')
        if username.strip() and password == repassword:
            query = User.all().filter('username =', username)
            if query.count()==0:
                user = User()
                user.username = username
                user.password = password
                user.running = False
                user.put()
                logging.info("%s Regist success!"%username)
                msg = u'注册成功,请在右侧登录！'
            else:
                msg = u'该用户已经注册,请重新注册'
        else:
            msg = u'字段不能为空,两次密码必须一致'
        self.render('template/weather/index.html',{'msg':msg})

class ActiveFetion(BaseRequestHandler):
    @checkLogin
    def post(self):
        msg = ''
        mobile_no = self.request.get('mobile_no')
        mobile_pwd = self.request.get('mobile_pwd')
        status = self.request.get('status')
#        logging.info('************'+mobile_no+'**********'+mobile_pwd)
        if mobile_no and mobile_pwd:
            user = User.get(getUserKey(self))
            user.mobile_no = mobile_no
            user.mobile_pwd = mobile_pwd
            if status == "True" :
                user.running = False
            else:
                user.running = True
            user.put()
            self.redirect('/admin')
        else:
            msg = u'手机号码和飞信密码不能为空'
        self.render('template/weather/user.html',{'msg':msg})

class TestFetion(BaseRequestHandler):
    @checkLogin
    def get(self):
        msg = ''
        user = User.get(getUserKey(self))
        if not user.running:
            msg = u'请先激活'
            self.render('template/weather/user.html',{'msg':msg})
        if user.mobile_no and user.mobile_pwd:
            fetion = TmpFetion(user.mobile_no,user.mobile_pwd)
            fetion.send_msg(user.mobile_no, u'收到本消息,说明服务启用正常!')
            self.redirect('/admin')
        else:
            msg = u'请先填写您的手机号和飞信密码!'
        self.render('template/weather/user.html',{'msg':msg})

class SendList(BaseRequestHandler):
    @checkLogin
    def get(self):
        user = User.get(getUserKey(self))
        if not user.running:
            msg = u'您的飞信尚未激活!请先激活飞信'
            self.render('template/weather/user.html',{'msg':msg})
        else:
            citys = City.all()
            list = user.sendusers_set
#            logging.info('*****************'+str(list.count()))
            self.render('template/weather/sender.html',{'list':list,'citys':citys})
    
    @checkLogin
    def post(self):
        msg = ''
        name = self.request.get('name')
        number = self.request.get('number')
        city = self.request.get('city')

        #检查此号码是否已经存在
        if name and number and city :
            query = SendUsers.all().filter('user =', getUserKey(self)).filter('number =', number)
            if query.count()>0:
                msg = u'该号码已添加,请勿重复添加'
            else:
                sender = SendUsers()
                sender.name = name
                sender.number = number
                sender.city = City.get(city)
                sender.user = User.get(getUserKey(self))
                sender.put()
                self.redirect('/admin/sendusers')
        else:
            msg = u'手机号码和城市拼音不能为空'
        self.render('template/weather/sender.html',{'msg':msg})

class DeleteSenders(BaseRequestHandler):
    @checkLogin
    def post(self):
        keys = self.request.get_all('list')
        for k in keys:
            query = SendUsers.get(k)
            if query.user.username == getUsername(self):
                query.delete()
        self.redirect('/admin/sendusers')

class QuickFetion(BaseRequestHandler):
    @checkLogin
    def get(self):
        send_list = User.get(getUserKey(self)).sendusers_set
        for s in send_list:
            log = FetionLog()
            log.sendname = s.name
            log.senddate = datetime.datetime.now()
            log.username = s.user.username
            log.weather = WeatherStore.all().filter('date =',today_str()).filter('city =',s.city.key())[0]
            try:
                fetion = TmpFetion(s.user.mobile_no,s.user.mobile_pwd)
                fetion.send_msg(s.number,makeWeather(s.city,today_str()).message)
                log.status = 'success'
            except:
                log.status = 'failture'
            log.put()
        self.redirect('/admin/sendusers')


class AutoWeather(BaseRequestHandler):
    '''
    每天定时采集天气情况
    '''
    def get(self):
        logging.info('***************start auto weather %s***************'%today_str())
        citys = City.all()
        for c in citys:
            makeWeather(c,today_str())
        logging.info('***************end auto weather***************')

class AutoFetion(BaseRequestHandler):
    import datetime
    def get(self):
        senders = SendUsers.all()
        logging.info('***************start auto fetion***************')
        for s in senders:
            if s.user.running:
                log = FetionLog()
                log.sendname = s.name
                log.senddate = datetime.datetime.now()
                log.username = s.user.username
                log.weather = makeWeather(s.city,today_str())
                try:
                    fetion = TmpFetion(s.user.mobile_no,s.user.mobile_pwd)
                    fetion.send_msg(s.number,makeWeather(s.city,today_str()).message)
                    log.status = 'success'
                except:
                    log.status = 'failture'
                log.put()
        logging.info('***************end auto fetion***************')



                

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/regist',Registe),
                                      ('/login',Login),
                                      ('/admin',AdminPage),
                                      ('/admin/active',ActiveFetion),
                                      ('/admin/test',TestFetion),
                                      ('/admin/sendusers',SendList),
                                      ('/admin/deletesenders',DeleteSenders),
                                      ('/admin/quickSend',QuickFetion),
                                      ('/autofetion',AutoFetion),
                                      ('/autoweather',AutoWeather)                                      
                                      ],debug=True)




def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
#    weather = Weather('hangzhou123213')
#    print weather.get_weather()